#include <iostream>
#include <unistd.h>
#include <cstring>
#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"InetAddr.hpp"

// 客户端不需要也不能显式绑定IP与port，由OS来做
// 客户端需要输入服务器的主机号与端口号

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "severip severport!\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return -1;
    }
    // 创建套接字描述符
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // ipv4,udp
    if (sockfd < 0)                              // 获取失败
    {
        Log(FATAL, "client sockfd get fail,[%s,%d]", strerror(errno), errno);
        exit(-1);
    }
    Log(DEBUG, "client sockfd get success...");

    std::string IP = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 获取网络字节序并存入套接字结构体
    struct sockaddr_in sever;
    sever.sin_addr.s_addr = inet_addr(IP.c_str());
    sever.sin_port = htons(port);
    sever.sin_family = AF_INET;

    Log(DEBUG, "UdpClient already start success...");

    while (true)
    {
        std::string message;
        std::cout<<"Enter your message# ";
        std::getline(std::cin, message);

        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        // 发送
        sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&sever, len);
        std::cout<<"发送成功"<<std::endl;
        // 接收
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "sever echo# " << buffer<<std::endl;
        }
    }
    return 0;
}
